let $;
let tableRender;
let paramQuery;
let indexTips;
let cols;
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'laydate'], function (exports) {
     $ = layui.$;
    let layer = layui.layer;
    let table = layui.table;
    let form = layui.form;
    let layDate = layui.laydate;
    let laypage = layui.laypage;
    let element = layui.element;
    cols = [
        [
            {field: 'batchId',title: '批次id', fixed: 'left', width: 175, align: 'center'},
            {field: 'batchName', title: '批次名称',fixed: 'left', width: 175, align: 'center',event:'showBatch' },
            {field: 'showName', title: '展示名称', width: 175, align: 'center', templet:row=>{
                    return row.showName ? row.showName : "--" ;
                }},
            {field: 'preferentialType', title: '优惠类型',width: 175, align: 'center',templet : function (row) {
                var value = "";
                if (row.preferentialType && row.preferentialType == 1) {
                    value = "折扣";
                }
                if (row.preferentialType && row.preferentialType == 2) {
                    value = "立减";
                }
                return value;
            }},
            {field: 'preferentialValue', title: '面值', width: 175,align: 'center', templet: function (row) {
                var value = "";
                if (row.preferentialValue) {
                    if (row.preferentialType && row.preferentialType == 1){
                        value = row.preferentialValue/10 + "折";
                    }
                    if (row.preferentialType && row.preferentialType == 2) {
                        value = (row.preferentialValue/100) + "元";
                    }
                }
                return value;
            }},
            {field: 'number', title: '数量', width: 175, align: 'center', templet: function (row) {
                var value = "--";
                if (row.number && row.number > 0){
                    value = row.number;
                }
                return value;
            }},
            {field: 'useType', title: '使用类型', width: 175, align: 'center', templet: function (row) {
                    var value = "";
                    if (row.useType && row.useType == 1){
                        value = "支付宝无资金";
                    }
                    else{
                        value = "其他";
                    }
                    return value;
                }},
            {field: 'redeemCodeGenerate', title: '是否生成兑换码', width: 175, align: 'center', templet: function (row) {
                    var value = "";
                    if (row.redeemCodeGenerate && row.redeemCodeGenerate == 2){
                        value = "生成";
                    }
                    else{
                        value = "不生成";
                    }
                    return value;
                }},
            {field: 'redeemCodeNumber', title: '兑换码生成数量', width: 175, align: 'center', templet:row=>{
                    return row.redeemCodeNumber ? row.redeemCodeNumber : 0 ;
                }},
            {field: 'issuedNum', title: '已发放',width: 175,  align: 'center', templet: function (row) {
                var  value = "--";
                if(row.issuedNum){
                    value = row.issuedNum;
                }
                return value;
            }},
            {field: 'usedNum', title: '已使用', width: 175, align: 'center', templet: function (row) {
                var  value = "--";
                if(row.usedNum){
                    value = row.usedNum;
                }
                return value;
            }},
            {field: 'invalidNum', title: '已失效', width: 175, align: 'center', templet: function (row) {
                var  value = "--";
                if(row.invalidNum){
                    value = row.invalidNum;
                }
                return value;
            }},
            // {field: 'activateWay', title: '激活方式', align: 'center', templet: function (row) {
            //     var  value = "";
            //     if(row.activateWay){
            //         if (row.activateWay == 11 ) {
            //             value = "新用户注册"
            //         }
            //         if (row.activateWay == 21 ) {
            //             value = "用户领取"
            //         }
            //         if (row.activateWay == 31 ) {
            //             value = "第三方-点评网"
            //         }
            //     }
            //     return value;
            // }},
            {field: 'usefulLifeBegin', title: '有效期',width: 175,  align: 'center', templet: function (row) {
                var usefulLifeBegin = "";var usefulLifeEnd = "";
                if (row.usefulLifeBegin){
                    usefulLifeBegin = zmnUtil.createTime(row.usefulLifeBegin);
                }
                if (row.usefulLifeEnd) {
                    //固定期限
                    usefulLifeEnd = "--" + zmnUtil.createTime(row.usefulLifeEnd);
                }
                if(row.expiryType==2){
                    //固定时长
                    usefulLifeEnd = "至"+row.effectiveDays+"天内有效";
                }
                return usefulLifeBegin + usefulLifeEnd;
            }},
            {field: 'costDeptName', title: '部门信息',width: 175,  align: 'center'},
            {field: 'createTime', title: '创建时间', width: 175, align: 'center', templet: function (row) {
                var createTime = "";
                if (row.createTime){
                    createTime = zmnUtil.createTime(row.createTime);
                }
                return createTime;
            }},
            {field: 'status', title: '状态',fixed:'right', width: 175, align: 'center', templet: function (row) {
                var value = ";"
                if (row.status) {
                    if (row.status == 1) {
                        value = "已创建";
                    }
                    if (row.status == 2) {
                        value = "已生效";
                    }
                    if (row.status == 3) {
                        value = "已关闭";
                    }
                    if (row.status == 4) {
                        value = "已删除";
                    }
                }
                return value;
            }},
            {field: 'right', fixed: 'right', title: '操作', width: 55, toolbar: '#barDemo'},
        ]
    ];

    /**
     * 描述: 时间初始化
     **/
      layDate.render({
            elem: '#startAndEndDate',
            range: true
       });



    /**
     * 描述: 表单初始化
     **/
    tableRender = function () {

        table.render({
            elem: "#zmn-coup-table",
            toolbar: "#zmn-coup-table-tool",
            title: "分类列表",
            data: json.items,
            limit: json.pageSize,
            cols: cols,
            page: true,
            height: 'full-120',
            done: function (res) {
                $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
            }
        });

        //分页加载数据，必须在表格初始化后
        laypage.render(zmnPage.laypageOptions(json));

    };

    tableRender();
    // location.reload(true);


  
    /**
     * 描述: 表单提交事件
     **/
    // form.on('submit(query-submit)', function (obj) {
        // paramQuery = obj.field;
        // tableRender(paramQuery);
        // zmnLayUtil.layTableRender(table, cols, "zmn-coup-table", {}, "/coup/batch/list.action",{limit:50,page:true});
        // return false;
    // });

    /**
     * 描述: 表单加载方法
     **/
    // tableRender = function (data) {
    //     zmnLayUtil.layTableRender(table, cols, "zmn-coup-table", data, "/coup/batch/loadData.action",{limit:50,page:true});
    // };


    /**
     * 描述: 表单初始化
     **/
    // tableRender({});

    /**
     * 描述: 新增批次
     **/
    $(document).on('click', '#addCoupBatch ', function () {
        zmnLayUtil.openIframeCustom(layer, "/coup/batch/addEditView.action", {shade: 1,area: ['100%', '100%'], end: endCallback});
    });
    //窗口关闭回调
    function endCallback(){
        layui.$("#query-submit").click();
    }

    //监听行工具事件
    // table.on('tool(zmn-coup-table)', function (obj) {
    $("[id^=showMenu-]").click(function (obj) {
        var batchId = this.id.split('-')[1];
        var status = $(this).attr("status");
        var redeemCodeGenerate = $(this).attr("redeemCodeGenerate");
        // if (obj.event === 'operation') {
            var row = new Object();
            row.batchId = batchId;
            row.status = status;
            row.redeemCodeGenerate = redeemCodeGenerate;
            $("#toolBar").append('<div class="layui-btn-container">' + loadMasterMenus(eval(row)) + '</div>');
        indexTips = layer.tips($("#toolBar").html(), this, {
            shade: [0],
            shadeClose: true,
            area: ['350px', '200px'],
            time: 0, //20秒后自动关闭
            tips: [3, '#FFFFFF'],
        });
        //     openMenuDiv(row.batchId);

        // 每次弹框结束后都要清空toolBar
        $("#toolBar").empty();
        // if(obj.event === 'showBatch'){
        //     zmnLayUtil.openIframeCustom(layer, "/coup/batch/addEditView.action?batchId="+obj.data.batchId +"&show=false", {title: "详情", shade: 0.8});
        // }
    });

    function loadMasterMenus(row) {
        let html = "";
        //修改、发布、删除
        if (row.status == 1||row.status == 2){
            if(row.status == 1){
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='editBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ");'>修改优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='releaseBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ");'>发布优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='delBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ");'>删除优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
            }
            else{
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled  onclick='editBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ");'>修改优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\"  disabled='true'>发布优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
                html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                    "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                    "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>删除优惠</button>\n" +
                    "            </div>\n" +
                    "        </div>";
            }
        }
        else {
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>修改优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\"  disabled='true'>发布优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>删除优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
        }

        // 关闭优惠券
        if (row.status == 2) {
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='closeBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ")'>关闭优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
        }else {
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>关闭优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
        }

        //复制优惠券
        if (row.status == 3){
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='copyBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ")'>复制优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
        } else {
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>复制优惠</button>\n" +
                "            </div>\n" +
                "        </div>";
        }

        // 优惠券详情
        html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
            "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
            "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='showBatch("+ JSON.stringify(row).replace(/"/g, '&quot;') + ")'>优惠详情</button>\n" +
            "            </div>\n" +
            "        </div>";
        // 预生成优惠券,条件是：批次生效+需要产生兑换码
        if (row.status == 2 && row.redeemCodeGenerate == 2 ){
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='createItemPre("+ JSON.stringify(row).replace(/"/g, '&quot;') + ")'>发兑换码</button>\n" +
                "            </div>\n" +
                "        </div>";

        } else{
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>发兑换码</button>\n" +
                "            </div>\n" +
                "        </div>";
        }

        if (row.status == 2){

            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-normal\" onclick='addCoupQuery("+ JSON.stringify(row).replace(/"/g, '&quot;') + ")'>人工发放</button>\n" +
                "            </div>\n" +
                "        </div>";
        } else{
            html += "<div class=\"layui-col-md3 layui-col-sm4\">\n" +
                "            <div class=\"layui-form-item layui-form-item-sm\">\n" +
                "                <button class=\"layui-btn layui-btn-sm layui-btn-disabled layui-btn-normal\" disabled='true'>人工发放</button>\n" +
                "            </div>\n" +
                "        </div>";
        }
        return html;

    }


    function openMenuDiv(batchId) {
        let selector = '#showMenu-' + batchId;
        indexTips = layer.tips($("#toolBar").html(), selector, {
            shade: [0],
            shadeClose: true,
            area: ['350px', '200px'],
            time: 0, //20秒后自动关闭
            tips: [3, '#FFFFFF'],
        });
    }

    // 启用/停用
    table.on("toolbar(zmn-coup-table)", function (obj) {

        if (obj.event == "CUSTOM_EXPORT"){
            console.info( $("#batch_form_list").serialize());

            var name ='优惠卷批次列表.xlsx';
            var arr=$("#batch_form_list").serializeArray();
            var fields=new Object;
            $.each(arr,function(k,v){
                fields[v.name]=v.value;
            });

            zmnUtil.download("/coup/batch/list/outputExcel?" + $("#batch_form_list").serialize(), name, function () {
                layer.close();
            });
            return;
        }
    });

    form.on('submit(zmn-form-reset)', function (obj) {
        $("#batchName").val("");
        $("#coupType").val("");
        $("#startAndEndDate").val("");
        $("#status").val("");
        form.render();
        return false;
    });



    //对外暴露的接口
    exports('batch_list', {});
});


    /**
     * 描述: 修改批次
     **/
    function editBatch(row){
        layer.close(indexTips);
        zmnLayUtil.openIframeCustom(layer, "/coup/batch/addEditView.action?batchId="+row.batchId,
            {title: "修改批次", shade: 1, area: ['100%', '100%'],});
    }

    function delBatch(row){
        layer.confirm('此优惠是否删除？', {
            btn: ['确定'] //按钮
        }, function(){
            $.ajax({
                type: "POST",
                url: "/coup/batch/deleteBatch.action",
                data: {batchId:row.batchId},
                success: function (json) {
                    if (json.status == 200) {
                        layer.close(indexTips);
                        // tableRender();
                        location.reload(true);
                    }
                    layer.msg(json.message);
                }
            });
        });
    }

    /**
     * 描述: 关闭批次
     **/
    function closeBatch(row){
        layer.confirm('确定关闭该批次？', {
            btn: ['确定'] //按钮
        }, function(){
            $.ajax({
                type: "POST",
                url: "/coup/batch/closeBatch.action",
                data: {batchId:row.batchId},
                success: function (json) {
                    if (json.status == 200) {
                        layer.close(indexTips);
                        // tableRender();
                        location.reload(true);
                    }

                    layer.msg(json.message);
                }
            });
        });
    }

    /**
     * 描述: 发布优惠券
     **/
    function releaseBatch(row){
        layer.confirm('发布优惠券？', {
            btn: ['确定'] //按钮
        }, function(){
            $.ajax({
                type: "POST",
                url: "/coup/batch/releaseBatch.action",
                data: {batchId:row.batchId},
                success: function (json) {
                    if (json.status == 200) {
                        layer.close(indexTips);
                        // tableRender();
                        location.reload(true);
                    }
                    layer.msg(json.message);
                }
            });
        });
    }

    function addCoupQuery(row) {

        var url = '/coup/coupquery/add.action?batchId=' + row.batchId;
        // var url = '/activity/config/coupinfo/add.action?activityId=' + json.currentActivityId;
        zmnLayUtil.openIframeCustom(layer, url, {title: "人工发放", shade: 0.8});
    }

    function refresh() {
        tableRender();
    }

    /**
     * 描述: 复制优惠券
     **/
    function copyBatch(row){
        layer.confirm('复制优惠券？', {
            btn: ['确定'] //按钮
        }, function(){
            $.ajax({
                type: "POST",
                url: "/coup/batch/copyBatch.action",
                data: {batchId:row.batchId},
                success: function (json) {
                    if (json.status == 200) {
                        layer.close(indexTips);
                        // tableRender();
                        location.reload(true);
                    }
                    layer.msg(json.message);
                }
            });
        });
    }
    function showBatch(row){
        layer.close(indexTips);
        zmnLayUtil.openIframeCustom(layer, "/coup/batch/addEditView.action?batchId="+row.batchId +"&show=false", {title: "详情", shade: 0.8});
    }
/**
 * 描述: 预生成优惠券
 **/
function createItemPre(row){
        layer.confirm(
            '              <form method="post" action="" class="layui-form" id ="zmn-batch-redeemCode-form"  lay-filter="zmn-batch-redeemCode-form" enctype="multipart/form-data">\n'+
            '                    <div class="layui-form-item layui-form-item-sm">\n' +
            '                        <label class="layui-form-label  layui-form-required">请输入本次兑换数量</label>\n' +
            '                        <div class="layui-input-block">\n' +
            '                               <input type="number" name="thisRedeemCodeNumber" id="thisRedeemCodeNumber" placeholder="最大值2500" class="layui-input"  lay-verify = "required|max_2500" min="1" max="2500">\n' +
            '                        </div>\n' +
            '                    </div>\n'+
            '                </form>',
            {
                btn: ['确定']
            } ,//按钮
            function(){
                // var redeemCodeForm = $("#zmn-batch-redeemCode-form");
                // zmnLayUtil.layFormVerify(redeemCodeForm);
                    row.thisRedeemCodeNumber = $("#thisRedeemCodeNumber").val();
                    if (row.thisRedeemCodeNumber&&row.thisRedeemCodeNumber>0&&row.thisRedeemCodeNumber<=2500){
                        $.ajax({
                            type: "POST",
                            url: "/coup/batch/createItemPreByBatchId.action",
                            data: {batchId:row.batchId,thisRedeemCodeNumber:row.thisRedeemCodeNumber},
                            success: function (json) {
                                if (json.status == 200) {
                                    layer.close(indexTips);
                                    // tableRender();
                                    location.reload(true);
                                }

                                layer.msg(json.message);
                            }
                        })
                    }
                    else{
                      // alert("请输入1-2500的值");
                       layer.alert("数值为1-2500，请重新发放",{icon:2});
                    }
            }
        )
}
